package service

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"im/define"
	"im/helper"
	"im/models"
	"log"
	"net/http"
)

var upgrader = websocket.Upgrader{} // use default options
// 保存所有连接过来的conn
var wc = make(map[string]*websocket.Conn)

func WebsocketMessage(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "系统异常: " + err.Error(),
		})
		return
	}
	defer conn.Close()
	uc := c.MustGet("user_claims").(*helper.UserClaims)
	wc[uc.Identity] = conn
	for {
		ms := new(define.MessageStruct)
		err := conn.ReadJSON(ms)
		if err != nil {
			log.Printf("Read Error : %v\n", err)
			return
		}
		// TODO: 判断用户是否属于消息体的房间
		_, err = models.GetUserRoomByUserIdentityRoomIdentity(uc.Identity, ms.RoomIdentity)
		if err != nil {
			log.Printf("UserIdentity:%v RoomIdentity:%v Not Exitis\n", uc.Identity, ms.RoomIdentity)
			return
		}
		// TODO: 保存消息
		// TODO: 获取在特点房间的在线用户
		for _, cc := range wc {
			err := cc.WriteMessage(websocket.TextMessage, []byte(ms.Message))
			if err != nil {
				log.Printf("Write Message Error : %v\n", err)
				return
			}
		}
	}
}
